<template>
  <div class="app-container">
    <div>
      <el-row>
        <el-col :span="4">
          <strong style="font-size: 20px;">
            新增/修改
          </strong>
        </el-col>
      </el-row>

      <div style="padding:20px">
        <el-form ref="form" v-loading="loading" :model="form" label-width="80px" element-loading-text="加载中...">
          <el-form-item label="用户名">
            <el-input v-model="form.name" :disabled="true" />
          </el-form-item>
          <el-form-item label="滞留金额">
            <el-input v-model="form.reserved" type="number" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.comment" />
          </el-form-item>
          <el-form-item label="是否激活">
            <el-checkbox v-model="form.enabled" />
          </el-form-item>
          <el-form-item label="配置">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="addItem()"
            >
              增加
            </el-button>
            <div v-for="(property, index) in items" :key="index">
              <p circle style="float: right">
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  circle
                  @click="deleteItem(index)"
                />
              </p>
              <div class="formDiv">
                <div class="formItem">
                  <div class="formItemLeft">提现账户</div>
                  <div class="formItemRight">
                    <el-select
                      v-model="property.account"
                      style="width: 100%;"
                      @change="$forceUpdate()"
                    >
                      <el-option
                        v-for="item in accounts"
                        :key="item.id"
                        :label="item.outAcntNm+'('+item.mobile+')'"
                        :value="item.id"
                      />
                    </el-select>
                  </div>
                </div>
              </div>
              <div class="formDiv">
                <div class="formItem">
                  <div class="formItemLeft">提现比例</div>
                  <div class="formItemRight">
                    <el-input v-model="property.proportion" type="number" />
                  </div>
                </div>

                <div class="help-text" style="display: flex;">
                  <div>
                    <p class="el-icon-info" />
                  </div>
                  <div>
                    <p v-html="'应填0-1小数，如10%为0.1'" />
                  </div>
                </div>
              </div>
              <el-divider content-position="left" />
            </div>
          </el-form-item>
        </el-form>
        <div style="float: right;padding-bottom: 20px;">
          <el-button type="primary" icon="el-icon-edit-outline" @click="onSubmit()">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: Number(this.$route.params.id),
      store: '',
      form: {
        user: '',
        name: '',
        reserved: '',
        comment: '',
        enabled: true
      },
      loading: false,
      disabled: false,
      deleteList: [],
      accounts: [],
      items: []
    }
  },
  created() {
    this.store = localStorage.getItem('storeId')
    this.getAccounts()

    if (this.id) {
      this.disabled = true
      if (this.store > 0) {
        this.loading = true
        this.axios.get(`/store/${this.store}/scheduled-withdraw-settings/${this.id}`, { params: {
          '@expands': `['entity.items']`
        }}).then((res) => {
          this.loading = false
          this.form.user = res.data.user.id
          this.form.name = res.data.user.__toString
          this.form.reserved = res.data.reserved
          this.form.comment = res.data.comment
          this.form.enabled = res.data.enabled

          const items = []
          for (var i of res.data.items) {
            items.push({ id: i.id, account: i.__metadata.account.id, proportion: i.__metadata.proportion })
          }
          this.items = items
        })
      }
    } else {
      this.axios.get(`/api/user`).then((res) => {
        this.form.user = res.data.id
        this.form.name = res.data.username
      })
    }
  },
  methods: {
    addItem() {
      const item = {}
      if (this.id) {
        item.setting = this.id
      }
      this.items.push(item)
    },
    deleteItem(index) {
      if (this.items[index].id) {
        this.deleteList.push(this.items[index].id)
      }
      this.items.splice(index, 1)
    },
    getAccounts() {
      if (this.store > 0) {
        this.axios.get(`/store/${this.store}/fuiou-accounts`).then((res) => {
          this.accounts = res.data
        })
      }
    },
    cleanBlankAttributes(data) {
      for (var propName in data) {
        if (data[propName] === null || data[propName] === undefined) {
          delete data[propName]
        }
      }
    },
    onSubmit() {
      if (this.store > 0) {
        const form = this.form
        const items = this.items
        const deleteList = this.deleteList
        if (!form.user) {
          this.$message.error('获取用户信息失败')
          return
        }
        if (!form.reserved) {
          this.$message.error('请填写滞留金额')
          return
        }
        if (items.length === 0) {
          this.$message.error('请配置提现账户')
          return
        }

        let amount = 0
        const data = []
        for (var i of items) {
          if (!i.account) {
            this.$message.error('存在未选择提现账户')
            return
          }
          if (!i.proportion) {
            this.$message.error('存在未填提现比例')
            return
          }
          amount += parseFloat(i.proportion)
          data.push(i)
        }
        if (amount > 1) {
          this.$message.error('累计比例超过1')
          return
        }

        const loading = this.$loading({
          lock: true,
          text: '数据交互中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.cleanBlankAttributes(form)
        if (this.id) {
          const promise = []
          promise.push(
            this.axios.put(`/store/${this.store}/scheduled-withdraw-settings/${this.id}`, form).then(res => {
              console.log('put', res)
            })
          )
          promise.push(
            this.axios.post(`/store/${this.store}/scheduled-withdraw-items/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }})
              .then((res) => {
                console.log('batch-update', res)
              })
          )
          if (deleteList.length > 0) {
            deleteList.forEach(v => {
              promise.push(
                this.axios.delete(`/store/${this.store}/scheduled-withdraw-items/${v}`)
                  .then((res) => {
                    console.log('delete', res)
                  })
              )
            })
          }
          Promise.all(promise).then((res) => {
            loading.close()
            this.$message.success('修改成功！')
            this.$router.go(-1)
          })
        } else {
          this.axios.post(`/store/${this.store}/scheduled-withdraw-settings`, form).then(res => {
            console.log('post', res)
            for (var i of data) {
              i.setting = res.data.id
            }
            this.axios.post(`/store/${this.store}/scheduled-withdraw-items/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }})
              .then((res) => {
                console.log('batch-update', res)
                loading.close()
                this.$message.success('修改成功！')
                this.$router.go(-1)
              })
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
    .help-text {
        display: flex;

        p {
            color: gray;
            line-height: 1.3em;
        }

        div {
            padding: 0 3px;
        }
    }

    .formDiv {
        white-space: nowrap;
        display: flex;
    }

    .formItem {
        width: 50%;
        display: flex;
        padding: 5px;
    }

    .formItemLeft {
        width: 20%;
    }

    .formItemRight {
        width: 90%;
    }
</style>
